<template>
  <div class="app-container">
    <el-form
      ref="elForm"
      :disabled="$route.query.isInfo"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="120px"
    >
      <h2 style="text-align: center">工作安排</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row>
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
            <el-cascader
              ref="reference"
              :props="{ value: 'id', checkStrictly: true }"
              placeholder="请选择部门"
              v-model="formData.deptId"
              :show-all-levels="false"
              :options="deptOptions"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="日期" prop="recordTime">
            <el-date-picker
              v-model="formData.recordTime"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作类型" prop="type">
            <el-select
              v-model="formData.type"
              placeholder="请选择工作类型"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in typeOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="table">
        <el-form-item
          label=""
          prop="form"
          style="margin-left: 0"
          label-width="0"
        >
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAddBox"
            v-if="!formData.workArrangementId"
            >增行</el-button
          >
          <el-table :data="formData.bos" :border="true" style="width: 100%">
            <el-table-column width="80" label="序号" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column width="250" label="工作安排" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.remark`"
                  :rules="rules.remark"
                >
                  <el-input
                    type="textarea"
                    v-model="scope.row.remark"
                    rows="3"
                    placeholder="工作安排"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="250" label="人员安排" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.examineUser`"
                  :rules="rules.examineUser"
                >
                  <el-input
                    type="textarea"
                    rows="3"
                    v-model="scope.row.examineUser"
                    placeholder="人员安排"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column width="180" label="选择车辆" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.id`"
                  :rules="rules.id"
                >
                  <el-select
                    filterable
                    multiple
                    v-model="scope.row.id"
                    placeholder="请选择选择车辆"
                    clearable
                    @change="changeCar($event, scope.$index)"
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(item, index) in carSelectList"
                      :key="index"
                      :label="item.licenseNum"
                      :value="item.carId"
                      :disabled="item.disabled"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="180" label="驾驶员" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.driverIds`"
                  :rules="rules.driverIds"
                >
                  <!-- <el-input v-model="scope.row.nickName" placeholder="请输入驾驶员" clearable
                    :style="{ width: '100%' }"></el-input> -->
                  <el-select
                    filterable
                    multiple
                    v-model="scope.row.driverIds"
                    placeholder="请选择驾驶员"
                    clearable
                    value-key="value"
                    @change="changeCarNamenick($event, scope.$index)"
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="(item, index) in selList"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="150" label="人员分配" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.userDistribute`"
                  :rules="rules.userDistribute"
                >
                  <el-input
                    v-model="scope.row.userDistribute"
                    rows="3"
                    placeholder="人员分配"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column width="150" label="司机分配" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.driverDistribute`"
                  :rules="rules.driverDistribute"
                >
                  <el-input
                    v-model="scope.row.driverDistribute"
                    rows="3"
                    placeholder="司机分配"
                    clearable
                    :style="{ width: '100%' }"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="附件" align="center">
              <template slot-scope="scope">
                <el-form-item
                  label-width="0"
                  :prop="`bos.${scope.$index}.attachmentUrl`"
                  :rules="rules.attachmentUrl"
                >
                  <FileUpload v-model="scope.row.attachmentUrl"></FileUpload>
                  <!-- <FileUploadBase
                    :isDelete="!$route.query.isInfo"
                    v-model="scope.row.attachmentUrl"
                  ></FileUploadBase> -->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              label="删除"
              align="center"
              v-if="!formData.workArrangementId"
            >
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  plain
                  size="mini"
                  @click="handleDeleBox(scope.$index)"
                  >删行</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>

      <el-col :span="24">
        <el-form-item
          label-width="0"
          style="text-align: center; margin-top: 30px"
        >
          <el-button
            v-if="!$route.query.isInfo"
            type="primary"
            @click="submitForm"
            >提交</el-button
          >
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import {
  workArrangementAdd,
  workArrangementEdit,
  workArrangementInfo,
} from "@/api/business/workArrangement.js";
import { selectList as carSelect } from "@/api/car/car.js";
import { selectList } from "@/api/car/driver.js";
import { deptTreeSelect } from "@/api/system/user.js";

export default {
  components: {},
  props: [],
  data() {
    return {
      carSelectList: [],
      deptOptions: [],
      typeOptions: [
        { label: "正常工作", value: "0" },
        { label: "加班", value: "1" },
      ],

      formData: {
        recordTime: "",
        deptId: "",
        type: "",
        bos: [
          {
            attachmentUrl: undefined,
            driverId: undefined,
            remark: "",
            examineUser: "",
          },
        ],
      },
      rules: {
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入工作安排",
            trigger: "change",
          },
        ],

        id: [
          {
            required: true,
            message: "请选择选择车辆",
            trigger: "blur",
          },
        ],
        driverIds: [
          {
            required: true,
            message: "请选择驾驶员",
            trigger: "change",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请选择出发时间",
            trigger: "change",
          },
        ],
        endTime: [
          {
            required: true,
            message: "请选择返回时间",
            trigger: "change",
          },
        ],
        operUserId: [
          {
            required: true,
            message: "请选择出车人",
            trigger: "change",
          },
        ],
        attachmentUrl: [
          {
            required: false,
            message: "附件不能为空",
            trigger: "change",
          },
        ],
        examineUser: [
          {
            required: true,
            message: "请输入人员安排",
            trigger: "change",
          },
        ],
        recordTime: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择工作类型",
            trigger: "change",
          },
        ],
      },
      selList: [],
    };
  },
  computed: {},

  created() {
    this.carSelect();
    this.getDeptTree();
    this.selectList();
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfo();
    }
  },
  mounted() {},
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    selectList() {
      selectList().then((res) => {
        let arr = [];
        res.data.forEach((item) => {
          const obj = {};
          obj.value = item.driverId;
          obj.label = item.nickName;
          arr.push(obj);
        });
        console.log(arr);
        this.selList = arr;
      });
    },
    handleAddBox() {
      this.formData.bos.push({
        attachmentUrl: undefined,
        contractCategoryValue: undefined,
        contractTypeValue: undefined,
      });
    },
    handleDeleBox(e) {
      if (this.formData.bos.length == 1) return;
      this.formData.bos.splice(e, 1);
    },
    changeCar(i, v) {
      let licenseNum = [];
      let carId = [];
      i.forEach((selectedCarId) => {
        const matchedCar = this.carSelectList.find(
          (car) => car.carId === selectedCarId
        );
        if (matchedCar) {
          licenseNum.push(matchedCar.licenseNum);
          carId.push(matchedCar.carId);
        }
      });
      this.formData.bos[v].carId = carId.toString();
      this.formData.bos[v].licenseNum = licenseNum.toString();
    },
    changeCarNamenick(i, v) {
      let nickName = [];
      let driverId = [];
      i.forEach((selectedCarId) => {
        const matchedCar = this.selList.find(
          (car) => car.value === selectedCarId
        );
        if (matchedCar) {
          nickName.push(matchedCar.label);
          driverId.push(matchedCar.value);
        }
      });
      this.formData.bos[v].driverId = driverId.toString();
      this.formData.bos[v].nickName = nickName.toString();
    },
    carSelect() {
      carSelect().then((response) => {
        this.carSelectList = response.data;
      });
    },
    getinfo() {
      workArrangementInfo(this.$route.query.id).then((response) => {
        this.formData = response.data;
        this.formData.type = response.data.type.toString();
        this.formData.deptId = Number(response.data.deptId);
        console.log(this.formData.deptId);

        this.formData.bos = response.data.vos.map((item) => {
          return {
            ...item,
            id: item.carId.split(",").map(Number),
            driverIds: item.driverId.split(",").map(Number),
          };
        });
      });
    },

    submitForm() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.deptId = this.$refs.reference.getCheckedNodes()[0].value;
          query.deptName = this.$refs.reference.getCheckedNodes()[0].label;
          if (this.formData.workArrangementId != undefined) {
            workArrangementEdit(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            workArrangementAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      this.$tab.closeOpenPage();
    },
  },
};
</script>
